//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type AckJoinDbItem struct {
	AckJoinId    string `bson:"_id"` //自动生成
	ProjectId    string `bson:"projectId"`
	MemberUserId string `bson:"memberUserId"`
	TimeStamp    int64  `bson:"timeStamp"`
}

type _AckJoinDao struct {
	mc *mongo.Collection
}

func newAckJoinDao(db *mongo.Database) (*_AckJoinDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT + "ack_join")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_AckJoinDao{mc: mc}, nil
}

func (db *_AckJoinDao) Insert(ctx context.Context, dbItem *AckJoinDbItem) error {
	dbItem.AckJoinId = db.genAckJoinId(dbItem.ProjectId, dbItem.MemberUserId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_AckJoinDao) genAckJoinId(projectId, memberUserId string) string {
	return fmt.Sprintf("%s:%s", projectId, memberUserId)
}

func (db *_AckJoinDao) Exist(ctx context.Context, projectId, memberUserId string) (bool, error) {
	ackJoinId := db.genAckJoinId(projectId, memberUserId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": ackJoinId, "projectId": projectId})
	return count > 0, err
}

func (db *_AckJoinDao) Remove(ctx context.Context, projectId, memberUserId string) error {
	ackJoinId := db.genAckJoinId(projectId, memberUserId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": ackJoinId, "projectId": projectId})
	return err
}

func (db *_AckJoinDao) ListByProject(ctx context.Context, projectId string) ([]*AckJoinDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []*AckJoinDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
